//
//  MLALShopFoodDetailVC.m
//  MagicLampApp
//
//  Created by Zheng on 2019/4/16.
//  Copyright © 2019 zheng.magic.lamp.app. All rights reserved.
//

#import "MLALShopFoodDetailVC.h"
#import "MLABaseFieldModel.h"
#import "MLABaseFieldView.h"
#import "MLAChoosePhotosView.h"
#import <TZImagePickerController.h>
#import "MLAShopFoodChooseTypeVC.h"

@interface MLALShopFoodDetailVC () <TZImagePickerControllerDelegate>

@property (nonatomic, strong) MLAEateryFoodTypeModel *model;


@end

@implementation MLALShopFoodDetailVC
{
    NSArray<MLABaseFieldModel *> *modelsArr;
    MLABaseFieldView *cateFieldView;
    MLAChoosePhotosView *photosView;
    NSMutableArray *photosArr;
    NSMutableArray *uploadArr;
    NSString *files;
    NSString *typeId;
    NSMutableDictionary *params;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    files = @"";
    
    if (_productId) {
        [self configTitle:@"编辑"];

    } else {
        [self configTitle:@"添加"];

    }
    
    photosArr = [NSMutableArray array];
    uploadArr = [NSMutableArray array];
    
    [self addSubviewsInView];
    
    @weakify(self);
    cateFieldView.clickActionBlock = ^{
        @strongify(self);
        MLAShopFoodChooseTypeVC *typeVC = [[MLAShopFoodChooseTypeVC alloc] init];
        [self.navigationController pushViewController:typeVC animated:YES];
        
        typeVC.chooseTypeBlock = ^(MLAEateryFoodTypeModel * _Nonnull model) {
            @strongify(self);
            NSLog(@"选择了分类%@",model.name);
            self.model = model;
            MLABaseFieldView *txf = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:14002];
            txf.inputText = model.name;
        };
    };
    
    if (_productId) {
        [self loadData];
    }
    
}

- (void)loadData {
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kShopProductProductDetail params:@{@"product_id":_productId} success:^(id  _Nonnull response, NSString * _Nonnull msg) {
//        productId = response[@"lists"][@"id"];
        
        MLABaseFieldView *txf0 = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:14000];
        txf0.inputText = response[@"lists"][@"name"];
        MLABaseFieldView *txf1 = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:14001];
        txf1.inputText = [NSString stringWithFormat:@"%.2f",[response[@"lists"][@"price"] doubleValue]/100.];

        MLABaseFieldView *txf2 = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:14002];
        txf2.inputText = response[@"lists"][@"product_type_name"];
        self.model = [[MLAEateryFoodTypeModel alloc] init];
        self.model.modelId = response[@"lists"][@"product_type"];

        [[[UIImageView alloc] init] sd_setImageWithURL:[NSURL URLWithString:response[@"lists"][@"product_imgs"]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            self->photosView.imagesArr = @[image];
            [self->photosArr addObject:image];
        }];
        
        
    } failure:^{
        
    }];
}

#pragma mark - LoadData
- (void)loadUpImagesData {
    
    UIImage *image = [uploadArr lastObject];
    NSData *fileData = UIImageJPEGRepresentation(image, 0.5);
    NSDictionary *params = @{@"file":fileData};
    
    [MLAHttpManage uploadHostType:MLAHttpHostType_Api api:kUploadFiles params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
//        self->files = [self->files stringByAppendingString:[NSString stringWithFormat:@",%@",response[@"file_url"]]];
        
        [self->params setObject:response[@"file_url"] forKey:@"product_imgs"];

//        [self->uploadArr removeLastObject];
//        if (self->uploadArr.count == 0) {
//            [self loadAddBillData];
//        } else {
//            [self loadUpImagesData];
//        }
        
        [self loadAddBillData];

        
    } failure:^{
        
    }];
}

- (void)loadAddBillData {
    
    
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kShopProductProductEdit params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        if (self.addSuccessBlock) {
            self.addSuccessBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^{
        
    }];
}


#pragma mark - Actions
- (void)commitBtnAction {
    
    NSString *name = [self getContentWithTag:14000];
    NSString *price = [self getContentWithTag:14001];

    if (name.length == 0) {
        [MLAHudManage showMessage:@"请输入菜品名称"];
        return;
    }
    
    if (price.length == 0) {
        [MLAHudManage showMessage:@"请输入价格"];
        return;
    }
    

    if (!self.model) {
        [MLAHudManage showMessage:@"请选择类型"];
        return;
    }
    
    
    params = [NSMutableDictionary dictionary];
    if (_productId) {
        [params setObject:_productId forKey:@"product_id"];
    }

    [params setObject:name forKey:@"name"];
    [params setObject:@(price.doubleValue*100) forKey:@"price"];
    [params setObject:_model.modelId forKey:@"product_type"];
    uploadArr = [photosArr mutableCopy];
    
    [self loadUpImagesData];
}

- (NSString *)getContentWithTag:(NSInteger)tag {
    MLABaseFieldView *fieldView = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:tag];
    return fieldView.inputText;
}


- (void)addPhotosDidClick {
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVC.allowCrop = YES;
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.cropRect = CGRectMake(0, (CX_GetScreenHeight()-CX_GetScreenWidth())/2., CX_GetScreenWidth(), CX_GetScreenWidth()*0.74);
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self->photosArr addObject:photos[0]];
        self->photosView.imagesArr = [self->photosArr copy];
    }];
}

- (void)deletePhotosDidClickWithDeleteIndex:(NSInteger)index {
    [photosArr removeObjectAtIndex:index];
    photosView.imagesArr = [photosArr copy];
}


#pragma mark - Subviews
- (void)addSubviewsInView {
    
    modelsArr = [self getModelsArr];
    
    CGFloat height = 660;
    
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.backgroundColor = CX_GetColorHex(0xFCFCFC, 1);
    tableHeaderView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), height);
    
    [modelsArr enumerateObjectsUsingBlock:^(MLABaseFieldModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MLABaseFieldView *fieldView = [[MLABaseFieldView alloc] init];
        fieldView.tag = 14000+idx;
        fieldView.model = obj;
        [tableHeaderView addSubview:fieldView];
        
        if (idx == 0) {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(20);
                make.left.right.equalTo(tableHeaderView);
                make.height.mas_equalTo(85);
            }];
        } else {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                UIView *view = [tableHeaderView viewWithTag:14000+idx-1];
                make.left.right.height.equalTo(view);
                make.top.equalTo(view.mas_bottom);
            }];
        }
        
        if (idx == 2) {
            self->cateFieldView = fieldView;
        }
    }];
    
    photosView = [[MLAChoosePhotosView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewLayout alloc] init]];
    photosView.title = @"上传图片：";
    [tableHeaderView addSubview:photosView];
    [photosView mas_makeConstraints:^(MASConstraintMaker *make) {
        UIView *view = [tableHeaderView viewWithTag:14000+self->modelsArr.count-1];
        make.top.equalTo(view.mas_bottom);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(CX_GetXScale(105));
    }];
    @weakify(self);
    photosView.photosViewDidClickAdd = ^{
        @strongify(self);
        [self addPhotosDidClick];
    };
    photosView.photosViewDidClickDetele = ^(NSInteger index, NSInteger tag) {
        @strongify(self);
        [self deletePhotosDidClickWithDeleteIndex:index];
    };
    
    UIButton *commitBtn = [self getCommitButtonWithTitle:@"提交"];
    [commitBtn addTarget:self action:@selector(commitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [tableHeaderView addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->photosView.mas_bottom).offset(30);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(40);
    }];
    
    
    self.tableView.tableHeaderView = tableHeaderView;
    [tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(CX_GetScreenWidth());
        make.height.mas_equalTo(height);
    }];
    
}

- (NSArray<MLABaseFieldModel *> *)getModelsArr {
    
    NSArray *infosArr = @[CX_GetFieldInfoDic(@"菜品名称：", @"输入菜品名称", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"价格：", @"输入价格", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"类型：", @"选择类型", @"30", @"0", @"0", @"1", @"")];
    return [[MLABaseFieldModel mj_objectArrayWithKeyValuesArray:infosArr] copy];
}




@end
